package com.lyrcsoft.handler;


import com.lyrcsoft.model.po.User;
import com.lyrcsoft.repository.UserRepository;
import javax.annotation.Resource;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

@Component
public class UserHandler {

    @Resource
    UserRepository userRepository;

    public Mono<ServerResponse> getAllUsers(ServerRequest serverRequest) {
        return ServerResponse.ok().contentType(org.springframework.http.MediaType.APPLICATION_JSON)
            .body(userRepository.findAll(), User.class);
    }

    public Mono<ServerResponse> addUser(ServerRequest serverRequest) {
        return ServerResponse.ok().contentType(org.springframework.http.MediaType.APPLICATION_JSON)
            .body(userRepository.saveAll(serverRequest.bodyToMono(User.class)), User.class);
    }

    public Mono<ServerResponse> deleteUser(ServerRequest serverRequest) {
        return userRepository.findById(Integer.valueOf(serverRequest.pathVariable("userId")))
            .flatMap(user -> userRepository.delete(user).then(ServerResponse.ok().build()))
            .switchIfEmpty(ServerResponse.notFound().build());
    }
}

